<template>
  <div style="position: absolute;left: 0;top: 0;bottom: 0;right: 0;" class="box-border">
    <!-- topTool -->
    <div class="h-[150px] flex flex-col p-3 bg-[rgb(255,254,255)]" style="position:absolute;top: 0;left: 0;right: 0;">
      <!-- seach -->

      <div class="flex w-full h-[60%] justify-between items-center">
        <div class="flex">
          <el-button type="primary" size="large" color="#153E76" @click="uploadDialog = true">
            <el-icon class="mr-1">
              <UploadFilled />
            </el-icon>
            上传文件
          </el-button>
          <el-button size="large" @click="dialogFormVisible = true">
            <el-icon class="mr-1">
              <FolderAdd />
            </el-icon>
            新建文件夹
          </el-button>
          <el-button size="large" v-show="checkList.length" @click="downloadAll">
            <el-icon class="mr-1">
              <Download />
            </el-icon>
            下载
          </el-button>
          <el-button size="large" type="primary" v-show="checkList.length === 1" @click="handleShare(checkList[0].id)">
            <el-icon class="mr-1">
              <Share />
            </el-icon>
            分享
          </el-button>
          <el-button size="large" type="success" v-show="checkList.length === 1" @click="renameFn">
            <el-icon class="mr-1">
              <EditPen />
            </el-icon>
            重命名
          </el-button>
          <el-button size="large" type="danger" v-show="checkList.length" @click="deleteItem(0)">
            <el-icon class="mr-1">
              <Delete />
            </el-icon>
            删除
          </el-button>
        </div>
        <div class="flex">
          <div class="mr-15" style="position: relative;">
            <el-input v-model="searchInput" @change="handleSearchNull" placeholder="搜索文件...." clearable size="large" />
            <el-button color="#153E76" style="position: absolute;border-radius:0 3px 3px 0" size="large"
              @click="handleSearch">
              <template #icon>
                <el-icon>
                  <Search />
                </el-icon>
              </template>
            </el-button>
          </div>
        </div>
      </div>
      <div class="flex items-stretch justify-start m-t-3 h-[30px] ">
        <el-breadcrumb separator=">" class="cursor-pointer">
          <el-breadcrumb-item class="cursor-pointer" @click="handleChangeTab({id:0})"><a class="cursor-pointer">首页</a>
          </el-breadcrumb-item>
          <el-breadcrumb-item class="cursor-pointer" v-for="tab in breadcrumbList" :key="(tab as any).id"
            @click="handleChangeTab(tab)">
            <a class="cursor-pointer">{{(tab as any).name}}</a>
          </el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <!-- allChecked -->
      <div class="h-[40%] flex items-center">
        <el-checkbox v-model="isChekeAll" @change="checkAllChange" label="全选" size="large" />
      </div>
    </div>
    <!-- main -->
    <div class="overflow-y-auto absolute left-0 right-0 top-[150px]  bottom-[0px] text-dark-900 "
      style="border: solid 1px #ccc;border-left: 0;border-right: 0;">
      <!-- 列表 -->
      <MediaList v-for="(item, index) in mediaArray" :key="item.id" :item="item" :index="index"
        @not-event="handleEvent"></MediaList>
      <el-empty description="空目录...." v-if="mediaArray.length === 0" />
    </div>
    <el-image-viewer :url-list="imgUrlList" :z-index=999 :hide-on-click-modal="true" v-if="shoImageView"
      :initial-index="showImageIndex" @close="handleImgClose" />

    <!-- 新建文件夹弹窗 -->
    <el-dialog v-model="dialogFormVisible" title="新建文件夹">
      <el-input v-model="createDirName" placeholder="请输入文件名" clearable></el-input>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="handleCreateDir">创建</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 上传文件弹窗 -->
    <el-dialog title="上传文件" v-model="uploadDialog" width="50%" @close="uploadSuccess">
      <el-upload class="upload-demo" drag :action="actionUrl" multiple :headers="uploadHeader" name="files">
        <el-icon class="el-icon--upload">
          <upload-filled />
        </el-icon>
        <div class="el-upload__text">
          拖拽文件 <em>或点击上传</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">
            请勿上传非法文件!
          </div>
        </template>
      </el-upload>
      <template #footer>
        <span>
          <el-button @click="uploadDialog= false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

  </div>
</template>

<script lang="ts" setup>
// 复制插件
import useClipboard from "vue-clipboard3";

import { ref, computed } from 'vue'
import MediaList from '../../components/media-list/index.vue'
import { ElNotification, ElMessageBox, ElMessage } from 'element-plus'
import userStore from '@/stores/user'
import fileStore from '@/stores/file'
import { postCreateDir, postRename, postAllDelete, getDownload, postShareCreate } from '@/service/api'

const { toClipboard } = useClipboard();
const UserStore = userStore()
const FileStore = fileStore()

// 请求容量
const searchInput = ref('')
const createDirName = ref('')
// 点击图片预览开启
const shoImageView = ref(false)
const dialogFormVisible = ref(false)
const uploadDialog = ref(false)
// 图片展示索引
const showImageIndex = ref(0)

const mediaArray = computed(() => FileStore.getFormatList)
const checkList = computed(() => mediaArray.value.filter((item: any) => item.checked))
const isChekeAll = computed(() => checkList.value.length === mediaArray.value.length)
const file_id = computed(() => {
  const len = UserStore.dirs.length
  if (len === 0) {
    return 0
  }
  return (UserStore.dirs[len - 1] as any).id
})
const breadcrumbList = computed(() => UserStore.dirs)

UserStore.userSize()
//  请求文件列表
FileStore.getFileList({ file_id: file_id.value })



const imgUrlList = ref([])
const actionUrl = computed(() => '/api/upload?file_id=' + file_id.value)
const uploadHeader = computed(() => ({ token: UserStore.token || '' }))

// 切换tab
const handleChangeTab = (item: any) => {
  if (item.id === 0) {
    UserStore.setdirs([])
    FileStore.getFileList({ file_id: file_id.value })
    return
  } else {
    const i = UserStore.dirs.findIndex((v: any) => v.id === item.id)
    if (i !== -1) {
      const arr = UserStore.dirs.slice(0, i + 1)
      UserStore.setdirs(arr)
      FileStore.getFileList({ file_id: file_id.value })
    }
  }
}

// 重命名
const renameFn = (e: any, index: any = false) => {
  console.log(`output->index`, index)
  const list = index !== false ? mediaArray.value[index] : checkList.value[0]

  ElMessageBox.prompt('', "", {
    inputValue: list.name,
    confirmButtonText: '修改',
    cancelButtonText: '取消',
  }).then(async ({ value = '' }) => {
    console.log(`output->value`, value)
    if (value == '') {
      ElNotification.success({
        title: '异常错误',
        message: "文件名不能为空",
        type: "warning",
        showClose: false,
      })
      return
    }
    // 改变
    await postRename({ id: list.id, name: value })
    FileStore.getFileList({})
    ElNotification.success({
      title: '操作通知',
      message: "修改成功",
      showClose: false,
    })
  }).catch((e: any) => {
    console.log(e);
  })

}
// 监听事件
const handleEvent = async (e: any) => {
  switch (e.type) {
    case 'delete':
      deleteItem(e.id)
      break;
    case 'checked':
      mediaArray.value[e.index].checked = e.value
      break
    case 'rename':
      renameFn(null, e.index)
      break
    case 'itemClick':
      handleListClick(e.data)
      break
    case 'download':
      download(e.item.url, e.item.name)
      break
    case "share":
      handleShare(e.id)
      break
  }
}

const handleShare = async (id: number) => {
  try {
    const res = await postShareCreate(id)
    ElMessageBox.confirm(res.data.data, 'warning', {
      confirmButtonText: '复制链接',
      cancelButtonText: '确定',
      type: 'success'
    }).then(() => {
      toClipboard(res.data.data.replace('分享链接:', ""))
      ElNotification({
        title: '复制成功',
        type: 'success'
      })
    })
  } catch (error: any) {
    ElMessage({
      message: error,
      type: 'warning'
    })
  }


}



// 下载
const download = async (url: string, name: string) => {
  const res = await getDownload(url)
  if (!res.data) {
    ElMessage({
      message: '服务器错误,稍后重试!',
      type: "warning"
    })
    return
  }
  const URL = window.URL.createObjectURL(new Blob([(res.data as any)]))
  const link = document.createElement('a')
  link.style.display = 'none'
  link.href = URL

  link.setAttribute('download', name)
  link.click()
}
// 下载多个
const downloadAll = () => {
  checkList.value.forEach((item: any) => download(item.url, item.name))
  checkAllChange(false)
}
// 删除
const deleteItem = (id = 0) => {
  ElMessageBox.confirm('确认要删除改文件吗?', 'warning', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: "warning"
  }).then(async () => {
    const ids: any = id > 0 ? id : checkList.value.map(item => item.id).join(',')
    await postAllDelete(ids)
    FileStore.getFileList({ file_id: file_id.value })
    ElMessage({
      message: '删除成功',
      type: 'success'
    })
    // 确定删除
  }).catch(() => {
    // 取消
  })
}

// 搜索
const handleSearch = () => {
  if (searchInput.value === '') {
    FileStore.getFileList({ file_id: file_id.value })
    return
  }
  FileStore.getSearchList(searchInput.value)
}

const handleSearchNull = () => {
  if (searchInput.value === '') {
    FileStore.getFileList({ file_id: file_id.value })
    return
  }
}

// 文件上传成功
const uploadSuccess = () => {
  FileStore.getFileList({ file_id: file_id.value })
}

// 全选
const checkAllChange = (e: boolean) => {
  mediaArray.value.forEach((item: any) => item.checked = e)
}

// 列表点击
const handleListClick = (item: any) => {
  switch (item.type) {
    // 单机图片时，预览图片
    case 'image':
      // eslint-disable-next-line no-case-declarations
      const list: string[] = []
      mediaArray.value.forEach(item => {
        if (item.type === 'image') {
          list.push(item.url)
        }
      });
      (imgUrlList as any).value = list
      showImageIndex.value = 0
      shoImageView.value = true
      break
    case 'dir':
      // 切换目录
      UserStore.changeDir({ id: item.id, name: item.name })
      FileStore.getFileList({ file_id: file_id.value })
      break
  }


}

// 图片预览关闭事件
const handleImgClose = () => {
  shoImageView.value = false
  showImageIndex.value = 0
}

// 新建文件夹
const handleCreateDir = async () => {
  if (createDirName.value == '') {
    ElNotification({
      title: '文件名不能为空!',
      showClose: false,
      type: "warning"
    })
    return
  }
  try {
    await postCreateDir({ file_id: file_id.value, name: createDirName.value })
    ElNotification({
      title: '创建成功',
      showClose: false,
      type: "success"
    })
    dialogFormVisible.value = false
    createDirName.value = ''
    FileStore.getFileList({ file_id: file_id.value })
  } catch (error) {
    console.log(error)
  }

}

</script>

<style lang="scss">
.el-input__wrapper {
  border-radius: 3px 0 0 3px !important;
  outline: none;

  &.is-focus {
    box-shadow: 0 0 0 1px #153E76 inset;
  }
}
</style>